package cn.zhiquxing.excel;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.zhiquxing.vo.ImportData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DataProcessService {
    @Autowired
    private ThirdPartyService thirdPartyService;
    
    @Autowired
    private DataRepository dataRepository;
    
    // 线程池配置
    private final ExecutorService asyncProcessor = Executors.newFixedThreadPool(
        10, 
        new ThreadFactoryBuilder().setNamePrefix("data-processor-%d").build()
    );
    
    @Async
    public void processBatchData(List<ImportData> batchData) {
        CompletableFuture<?>[] futures = batchData.stream()
            .map(data -> CompletableFuture.runAsync(() -> processSingleData(data), asyncProcessor))
            .toArray(CompletableFuture[]::new);
        
        try {
            // 等待所有任务完成，设置超时时间
            CompletableFuture.allOf(futures).get(5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("批处理执行异常", e);
        }
        
        // 批量保存成功处理的数据
        List<ImportData> successData = batchData.stream()
            .filter(ImportData::getProcessed)
            .collect(Collectors.toList());
            
        if (!successData.isEmpty()) {
            dataRepository.batchSave(successData);
        }
    }
    
    private void processSingleData(ImportData data) {
        try {
            // 1. 调用第三方接口
            ThirdPartyResponse response = thirdPartyService.callApi(data);
            
            // 2. 验证响应
            if (response.isSuccess()) {
                data.setProcessed(true);
                // 可以设置第三方返回的数据
                data.setExternalId(response.getId());
            } else {
                data.setErrorMsg("第三方接口调用失败: " + response.getErrorMsg());
            }
        } catch (Exception e) {
            log.error("处理数据异常: {}", data, e);
            data.setErrorMsg("处理异常: " + e.getMessage());
        }
    }
}